<?php
include_once('../lib/config.php');
include_once('../lib/Db.class.php');
include_once('../lib/Model.class.php');
include_once('../lib/Snoopy.class.php');
include_once('../lib/function.php');
include_once('/usr/local/xunsearch/sdk/php/lib/XS.php');

//将未入数据库的搜索数据插入数据库
$redis = new Redis();
$ret = $redis->connect("localhost","6379");  //php客户端设置的ip及端口
if(!$ret) die('redis connction faild');
$redis->auth(REDIS_PASS);
$redis->select(2);

$GLOBALS['config']['master']['db_database'] = 'gouyg';
$GLOBALS['config']['slave']['db_database']  = 'gouyg';

$basedir = dirname(__FILE__);
$model = new Db;

$p = 1;
while (true) {
    try {
        $xs = new XS('books');
        $index  = $xs->index;
        $search = $xs->search;
        $search->setCharset('UTF-8');
        $search->setQuery('*');

        $p = max(1, intval($p));
        $n = XSSearch::PAGE_SIZE;
        $search->setLimit($n, ($p - 1) * $n);
        $docs = $search->search();

        $count = $search->getLastCount();
        $total = $search->getDbTotal();
        echo2('count:'.$count.', total:'.$total.', '.count($docs).", {$p}/{$n}");

        if($count == 0 || count($docs) == 0) break;

        foreach ($docs as $doc) {
            $book_data = [
                'md5id' => $doc->md5id,
                'title' => $doc->title,
                'description' => $doc->description,
                'classname' => $doc->classname,
                'typename' => $doc->typename,
                'author' => $doc->author,
                'addtime' => $doc->addtime,
                'info' => $doc->info,
                'thumb' => $doc->thumb,
                'download' => $doc->download,
                'indextime' => $doc->indextime,
            ];

            // 存储book信息
            $old_book = $model->find('ebook', "md5id='".$doc->md5id."'");
            if(!$old_book) {
                $r = $model->add('ebook', $book_data);
                if(!$r) {
                    $error = $model->error('ebook insert error');
                    throw new Exception($error['info']);
                } else {
                    $book_id = $model->insert_id();
                }
            } else {
                $book_id = $old_book['id'];
            }

            echo2('ebook_id:'.$book_id);

            continue;
        }
        $p++;

    } catch (Exception $e) {
        var_dump($e->getMessage());

        sleep(5);
    }
}

